package com.wzk.travelspringboot.common;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzk.travelspringboot.dao.BlogLikeDAO;
import com.wzk.travelspringboot.entity.BlogLike;
import com.wzk.travelspringboot.service.ScenicTypeService;
import com.wzk.travelspringboot.vo.ScenicTypeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/6 22:34
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppStartPre implements ApplicationRunner {

    private final StringRedisTemplate stringRedisTemplate;

    private final ScenicTypeService scenicTypeService;

    private final ObjectMapper objectMapper;

    private final BlogLikeDAO blogLikeDAO;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("应用正在启动......");
        stringRedisTemplate.execute((RedisCallback<Void>) connection -> {
            connection.flushAll();
            return null;
        });
        log.info("成功清除redis缓存");
        stringRedisTemplate.delete(RedisConstant.SCENIC_TYPE_KEY);
        List<ScenicTypeVO> typeVO = scenicTypeService.query().list().stream().map(st -> BeanUtil.copyProperties(st, ScenicTypeVO.class)).collect(Collectors.toList());
        stringRedisTemplate.opsForValue().set(RedisConstant.SCENIC_TYPE_KEY,objectMapper.writeValueAsString(typeVO),RedisConstant.SCENIC_TYPE_TIME, TimeUnit.MINUTES);
        log.info("scenicType已加载到缓存，一共"+typeVO.size()+"条");
        List<BlogLike> blogLikesData = blogLikeDAO.queryAll();
        if (!blogLikesData.isEmpty()){
            for (BlogLike likeData : blogLikesData) {
                stringRedisTemplate.opsForSet().add(RedisConstant.BLOG_LIKE_KEY+likeData.getBlogId(),likeData.getUserId()+"");
            }
            log.info("blogLike数据已加载到缓存，一共"+blogLikesData.size()+"条");
        }
    }
}
